<template>
  <div class="app-container">
    <div style="height: 4em;background-color: #fcfae6;border-left: 4px solid #f8ca15; padding: 20px">
      <span style="margin-left: 20px;">
        <i class="el-icon-warning"></i>
        解析成功后才能进行问答。
      </span>
    </div>
    <!--    <el-row :gutter="10" class="mb8">-->
    <el-row style="margin-top: 20px;margin-bottom: 20px">
      <el-col :span="1.5" style="float:right;padding-left: 10px">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="dialogVisibleFile = true">上传文件
        </el-button>
      </el-col>
      <el-col :span="1.5" style="float:right;">
        <el-input v-model="queryParams.keywords" placeholder="搜索文件" style="width: 200px;" @input="getList"/>
      </el-col>
      <!--    </el-row>-->
      <!--    <el-row style="margin-top: 20px;margin-bottom: 20px">-->
      <el-col :span="1.5">
        <el-button type="danger" @click="Batch(1)">批量删除</el-button>
        <el-button type="success" @click="Batch(2)">批量解析</el-button>
        <el-button type="warning" @click="Batch(3)">批量取消解析</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="fileList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="100" align="center"/>
      <el-table-column prop="name" align="center" label="名称" width="">
        <template slot-scope="scope">
          <router-link :to="{ path: '/rag/search', query: {datasetId:$route.query.datasetId, doc_id: scope.row.id, doc_name: scope.row.name} }">
            {{ scope.row.name }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column prop="chunk_count" align="center" label="分块数" width=""></el-table-column>
      <el-table-column label="上传日期" align="center" prop="createTime" width="">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="chunk_method" align="center" label="解析方法">
        <template slot-scope="scope">
          {{ getMethodName(scope.row.chunk_method) }}
        </template>
      </el-table-column>

<!--      <el-table-column label="启用" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <el-switch-->
<!--            v-model="scope.row.status"-->
<!--            active-value="1"-->
<!--            inactive-value="0"-->
<!--          ></el-switch>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" label="解析状态" width="">
        <template slot-scope="scope">
          <el-tag style="width: 5em;" :type="getRunName(scope.row.run).type">{{ getRunName(scope.row.run).name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.run == 'RUNNING'" class="item" effect="dark" content="停止解析" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-pause"
              @click="handleStopParse(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip v-else-if="scope.row.run == 'DONE'" class="item" effect="dark" content="已解析" placement="top">
            <el-button
              :disabled="scope.row.run == 'DONE'"
              size="mini"
              type="text"
              icon="el-icon-help"
            ></el-button>
          </el-tooltip>
          <el-tooltip v-else class="item" effect="dark" content="解析" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleParse(scope.row)"></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="下载" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-connection"
              @click="handleDownload(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>
    <!-- 修改对话框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="400px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" type="text" style="width: 240px"></el-input>
        </el-form-item>
        <el-form-item label="解析方法:" prop="chunk_method">
          <el-select v-model="form.chunk_method" placeholder="请选择嵌入模型" style="width: 240px">
            <el-option v-for="item in jxMothod" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择文件" :visible.sync="dialogVisibleFile" width="400px" append-to-body>
      <el-upload
        class="upload-demo"
        drag
        :file-list=addFileList
        :http-request="handleAdd"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>,支持批量上传，支持的文件类型为：txt,pdf,doc,docx,ppt,pptx,xls,xlsx,csv</div>
      </el-upload>
      <el-button style="margin-top: 10px;width: 100%" type="primary" @click="dialogVisibleFile = false">确 定
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  addFile,
  delChunks,
  delFile,
  downloadFile,
  editFile,
  getDataList,
  parseFile,
  setToken,
  stopParseFile
} from "@/api/rag/rag.js";



export default {

  data() {
    return {
      way: "批量导出",
      fileName: '',
      dialogVisible: false,
      jxMothod: [{name: 'General', value: 'naive'}, {name: 'Q&A', value: 'qa'}, {
        name: 'Knowledge Graph',
        value: 'knowledge_graph'
      }],
      option: [{name: '批量删除', value: '1'}, {name: '批量导出', value: '2'}, {name: '批量', value: '3'}],
      jxStatus: [{name: '未解析', value: "UNSTART", type: ''}, {
        name: '成功',
        value: 'DONE',
        type: 'success'
      }, {name: '取消', value: "CANCEL", type: 'danger'}, {name: '解析中', value: 'RUNNING', type: 'warning'}],
      fileList: [],
      addFileList: [],
      // 遮罩层
      loading: true,
      title: "",
      // 是否显示弹出层
      open: false,
      total: 0,
      form: {},
      selectedFileIds: [],
      selectedFileIdStr: [],
      dialogVisibleFile: false,
      queryParams: {
        // datasetId: 'c91bdf6cf80d11ef9da50242ac120006',
        datasetId: '',
        pageNum: 1,
        pageSize: 10,
        keywords: ''
      },
      editForm: {},
      fileBody: {
        name: '',
        chunk_method: '',
        // parser_config: {}
      },
    };
  },
  mounted() {
    const datasetId = this.$route.query.datasetId;
    console.log('接收到的datasetId:', datasetId);
    this.getSrc();
    // this.getList();
  },
  methods: {


    getSrc(){
      this.queryParams.datasetId=this.$route.query.datasetId;
      // this.key = this.$route.query.key;
      // if(this.key !== ''){
      //   setToken(this.key)
      if (this.queryParams.datasetId){
        this.getList()
      }
      // }
    },
    getMethodName(value) {
      const method = this.jxMothod.find(item => item.value === value);
      return method ? method.name : 'Unknown';
    },
    getRunName(value) {
      const status = this.jxStatus.find(item => item.value === value);
      return status;
    },
    getList() {
      this.loading = false;
      getDataList(this.queryParams.datasetId, this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.keywords).then(response => {
        this.fileList = response.data.docs;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      })
    },
    handleSelectionChange(selection) {
      this.selectedFileIdStr = [];
      this.selectedFileIds = selection.map(row => row.id);
      this.selectedFileIds.forEach((id) => {
        const idStr = id.toString()
        this.selectedFileIdStr.push(idStr)
      })
    },
    Batch(type) {
      if (this.selectedFileIds.length == 0) {
        this.$message({
          message: '请先选择文件',
          type: 'warning'
        });
      } else {
        if (type == 1) {
          // 删除
          delFile(this.queryParams.datasetId, this.selectedFileIdStr).then(() => {
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            });
          })
        } else if (type == 2) {
          // 解析
          parseFile(this.queryParams.datasetId, this.selectedFileIdStr).then(() => {
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            });
          })
        } else if (type == 3) {
          // 取消解析
          stopParseFile(this.queryParams.datasetId, this.selectedFileIdStr).then(() => {
            this.getList()
            this.$message({
              message: '操作成功',
              type: 'success'
            });
          })
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd(req) {
      if (req.file) {
        const file = req.file
        const formData = new FormData();
        formData.append('file', file);
        addFile(this.queryParams.datasetId, formData).then(() => {
          this.getList()
          this.loading = false
        })
      } else {
        console.log(req)
      }
      this.loading = true
    },
    handleParse(row) {
      this.selectedFileIdStr = []
      this.selectedFileIdStr.push(row.id.toString())
      // 删除所有chunk
      // this.selectedFileIdStr.forEach((id) => {
      //   if (id) {
      //     parseFile(this.queryParams.datasetId, id)
      //   }
      // })
      parseFile(this.queryParams.datasetId, this.selectedFileIdStr).then(() => {
        this.getList()
        this.$message({
          message: '操作成功',
          type: 'success'
        });
      })
    },
    handleStopParse(row){
      this.selectedFileIdStr = []
      this.selectedFileIdStr.push(row.id.toString())
      stopParseFile(this.queryParams.datasetId, this.selectedFileIdStr).then(() => {
        this.getList()
        this.$message({
          message: '操作成功',
          type: 'success'
        });
      })
      this.getList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "编辑文件"
      this.dialogVisible = true;
      this.form = row;
    },
    submitForm() {
      this.fileBody.name = this.form.name
      this.fileBody.chunk_method = this.form.chunk_method
      editFile(this.queryParams.datasetId, this.form.id, this.fileBody).then((res) => {
        this.dialogVisible = false
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.getList()
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$msgbox({
        title: '删除确认',
        message: '确认删除吗？',
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }).then(action => {
        if (action === "confirm") {
          const ids = [row.id]
          this.loading = true
          delFile(this.queryParams.datasetId, ids).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getList();
            this.loading = false
          })
        }
      });
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false;
    },
    handleDownload(row) {
      downloadFile(this.queryParams.datasetId, row.id,row.location).then(res => {
        let blob = new Blob([res],{type:"application/octet-stream;"})
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = row.location
        link.click()
        window.URL.revokeObjectURL(url)
      })
    }
  }
};
</script>
<style scoped>
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  border: 2px dashed #ccc;
  border-radius: 10px;
  cursor: pointer;
}

.upload-container input[type="file"] {
  display: none;
}

.upload-text {
  font-size: 16px;
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}
</style>

